<template>
  <fui-nav-bar
    isOccupy
    isFixed
    background="#0052D9"
    title="选择设备"
    color="#fff"
    @leftClick="leftClick"
  >
    <fui-icon color="#fff" name="arrowleft"></fui-icon>
  </fui-nav-bar>

  <view class="viewport">
    <view class="warp">
      <!-- 搜索框 -->
      <view class="head">
        <view class="ipt">
          <u--input
            v-model="searchValue"
            placeholder="请输入设备名称/编号"
            prefixIcon="search"
            prefixIconStyle="font-size: 22px;color: #909399"
            @change="handleSearch"
          ></u--input>
        </view>
      </view>

      <!-- 设备列表 -->
      <scroll-view
        class="scroll-view"
        :refresher-triggered="refreshing"
        refresher-enabled
        scroll-y="true"
        lower-threshold="20"
        @scrolltolower="onScrollToLower"
        @refresherrefresh="onRefresh"
        refresher-background="#f5f5f5"
      >
        <view class="port">
          <!-- 空状态 -->
          <view
            v-if="!deviceList.length && !loading"
            style="text-align: center; padding: 40rpx; color: #999"
            >暂无数据</view
          >

          <!-- 设备卡片列表 -->
          <view
            class="ul"
            v-for="(item, index) in deviceList"
            :key="index"
            @click="selectDevice(item)"
          >
            <view class="device-info">
              <image
                class="device-image"
                :src="item.image"
                mode="aspectFit"
              ></image>
              <view class="device-details">
                <view class="title">{{ item.deviceName }}</view>
                <view class="li">
                  <span class="left">设备编号</span>
                  <span>{{ item.deviceCode }}</span>
                </view>
                <view class="li">
                  <span class="left">使用部门</span>
                  <span>{{ item.department }}</span>
                </view>
                <view class="li">
                  <span class="left">存放位置</span>
                  <span>{{ item.location }}</span>
                </view>
              </view>
              <view class="select-indicator" v-if="selectedId === item.id">
                <view class="select-icon">
                  <fui-icon name="check" color="#fff" size="24"></fui-icon>
                </view>
              </view>
            </view>
          </view>

          <!-- 加载状态 -->
          <view
            v-if="loading"
            style="text-align: center; padding: 30rpx; color: #0052d9"
            >加载中...</view
          >
          <view
            v-if="noMore && deviceList.length"
            style="text-align: center; padding: 10rpx 20rpx 60rpx; color: #999"
            >没有更多了</view
          >
        </view>
      </scroll-view>
    </view>
  </view>

  <!-- 底部确定按钮 -->
  <view class="bottom-button">
    <button class="confirm-btn" @click="confirmSelection">确定</button>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getDeviceList } from "@/pages/api/subpkg_institution/repairworkorder.js";

// 搜索关键词
const searchValue = ref("");

// 筛选条件
const filters = ref({});

// 设备列表数据
const deviceList = ref([]);

// 选中的设备ID
const selectedId = ref("");

// 分页和加载状态
const refreshing = ref(false);
const loading = ref(false);
const noMore = ref(false);
const total = ref(0);
const current = ref(1);
const size = ref(10);

// 从页面参数中获取筛选条件
const getFilters = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.$page?.options;

  if (options?.filters) {
    try {
      filters.value = JSON.parse(decodeURIComponent(options.filters));
    } catch (error) {
      console.error("解析筛选条件失败:", error);
    }
  }
};

// 加载设备列表
const loadDeviceList = async (isRefresh = false) => {
  if (loading.value) return;
  loading.value = true;

  try {
    const params = {
      current: current.value,
      size: size.value,
      deviceName: searchValue.value || undefined,
      ...filters.value, // 添加筛选条件
    };

    const res = await getDeviceList(params);
    if (res.code === 200 && res.success) {
      // 处理返回的数据
      const newList = res.data.records.map((item) => ({
        id: item.id,
        deviceName: item.deviceName,
        deviceCode: item.deviceCode,
        department: item.deptName,
        location: item.storageLocation,
        image: item.picUrls || "/static/images/device/default.png",
        assetNumber: item.assetNumber,
        deviceType: item.deviceType,
        manufacturer: item.manufacturer,
        managerName: item.managerName,
      }));

      if (isRefresh) {
        deviceList.value = newList;
      } else {
        deviceList.value = [...deviceList.value, ...newList];
      }

      total.value = res.data.total || 0;
      noMore.value = deviceList.value.length >= total.value;
    } else {
      uni.showToast({
        title: res.msg || "获取设备列表失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取设备列表出错：", error);
    uni.showToast({
      title: "获取设备列表失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 返回上一页
const leftClick = () => {
  uni.navigateBack();
};

// 搜索处理
const handleSearch = () => {
  current.value = 1;
  deviceList.value = [];
  loadDeviceList(true);
};

// 选择设备
const selectDevice = (device) => {
  selectedId.value = device.id;
};

// 确认选择
const confirmSelection = () => {
  if (!selectedId.value) {
    uni.showToast({
      title: "请选择设备",
      icon: "none",
    });
    return;
  }

  const selectedDevice = deviceList.value.find(
    (item) => item.id === selectedId.value
  );
  if (!selectedDevice) {
    uni.showToast({
      title: "所选设备不存在",
      icon: "none",
    });
    return;
  }

  // 只传递设备 id 和名称
  uni.$emit("deviceSelected", {
    deviceId: selectedDevice.id,
    deviceName: selectedDevice.deviceName,
  });

  // 返回上一页
  uni.navigateBack();
};

// 滚动到底部加载更多
const onScrollToLower = () => {
  if (noMore.value || loading.value) return;
  if (deviceList.value.length >= total.value) {
    noMore.value = true;
    return;
  }
  current.value++;
  loadDeviceList();
};

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  current.value = 1;
  noMore.value = false;
  await loadDeviceList(true);
};

// 页面加载时获取筛选条件和设备列表
onMounted(() => {
  getFilters();
  loadDeviceList(true);
});
</script>

<style lang="scss" scoped>
page {
  display: flex;
  height: 100%;
  overflow: hidden;
  flex-direction: column;
}

.viewport {
  flex: 1;
  display: flex;
  overflow: hidden;
  flex-direction: column;
}

.warp {
  flex: 1;
  overflow: hidden;
  background-color: #f5f5f5;
  font-family: Arial, Helvetica, sans-serif;
  display: flex;
  flex-direction: column;

  .head {
    display: flex;
    align-items: center;
    background-color: #fff;
    height: 120rpx;
    padding: 20rpx;

    .ipt {
      flex: 1;
      margin-left: 25rpx;
      height: 100rpx;
      display: flex;
      align-items: center;
    }
  }

  /* #ifdef APP-PLUS || H5 */
  .scroll-view {
    flex: 1;
    height: 100%;
    padding-bottom: 220rpx;
  }
  /* #endif */

  /* #ifdef MP-WEIXIN */
  .scroll-view {
    height: 80vh;
  }
  /* #endif */

  .port {
    .ul {
      margin-bottom: 24rpx;
      background-color: #fff;
      padding: 30rpx;
      position: relative;
      overflow: hidden;

      &:active {
        opacity: 0.7;
      }

      .device-info {
        display: flex;
        position: relative;

        .device-image {
          width: 160rpx;
          height: 160rpx;
          border-radius: 8rpx;
          margin-right: 24rpx;
        }

        .device-details {
          flex: 1;

          .title {
            color: #0052d9;
            font-size: 35rpx;
            font-weight: 600;
            margin-bottom: 16rpx;
          }

          .li {
            color: #ccc;
            height: 50rpx;
            line-height: 50rpx;

            .left {
              color: #000;
              margin-right: 30rpx;
            }
          }
        }

        .select-indicator {
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          z-index: 1;

          .select-icon {
            width: 44rpx;
            height: 44rpx;
            border-radius: 50%;
            background-color: #0052d9;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
          }
        }
      }
    }
  }
}

.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .confirm-btn {
    background-color: #0052d9;
    color: #fff;
    border-radius: 8rpx;
    font-size: 32rpx;
    height: 88rpx;
    line-height: 88rpx;
  }
}
</style>
